<template>
    <div ref="container" style="width: 100%; height: 100%;"></div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

import * as dhx from 'dhx-suite';

import {
    Layout as dhxLayout,
    Toolbar as dhxToolbar,
    Sidebar as dhxSidebar,
    Tabbar as dhxTabbar,
    Grid as dhxGrid,
    DataView as dhxDataview,
    ContextMenu as dhxContextMenu,
} from 'dhx-suite'

import {
    systemLayoutConfig,
    systemSidebarConfig,
    systemTabbarConfig,
    topmenuData,
    sidebarData,
} from './components/layoutSystem.js'

import {
    loadAboutContent,
    boardAboutConfig,
} from './components/boardAbout.js'

import {
    boardHomeConfig,
    test2ContextMenuConfig,
    test2GridConfig,
    scanToolbarConfig,
    scanGridConfig,
    test2Data,
} from './components/boardHome.js'

import {
    boardClassConfig,
    classContextMenuConfig,
    classGridConfig,
    classToolbarConfig,
    studentDataviewConfig,
    studentToolbarConfig,
    allStudentsPool,
    classData,
} from './components/boardClass.js'

import {
    boardTestConfig,
    testToolbarConfig,
    testContextMenuConfig,
    testGridConfig,
    sheetToolbarConfig,
    sheetGridConfig,
    testData,
} from './components/boardTest.js'

// DOM引用
let container = ref(null);

// 系统模块实例
let layoutSystem = null;

let systemToolbarInstance = null;
let systemTabbarInstance = null;
let systemSidebarInstance = null;

// 关于模块实例
let boardAbout = null;

// 首页模块实例
let boardHome = null;

let test2GridInstance = null;
let test2ContextMenuInstance = null;

let scanToolbarInstance = null;
let scanGridInstance = null;

// 班级模块实例
let boardClass = null;

// 当前正在扫描的测试名称（供上传流程使用）
let currentScanTestName = null;

let classToolbarInstance = null;
let classGridInstance = null;
let classContextMenuInstance = null;

let studentToolbarInstance = null;
let studentDataviewInstance = null;

// 班级模块实例
let boardTest = null;

let testToolbarInstance = null;
let testGridInstance = null;
let testContextMenuInstance = null;

let sheetToolbarInstance = null;
let sheetGridInstance = null;

// 当前编辑的测试（用于下载按钮）
let currentEditingTest = null;
function initSystem() {
    if (!layoutSystem) {
        layoutSystem = new dhxLayout(container.value, systemLayoutConfig);

        systemToolbarInstance = new dhxToolbar(null);
        systemTabbarInstance = new dhxTabbar(null, systemTabbarConfig);
        systemSidebarInstance = new dhxSidebar(null, systemSidebarConfig);

        systemToolbarInstance.data.parse(topmenuData);
        systemSidebarInstance.data.parse(sidebarData);

        layoutSystem.getCell("toolbar").attach(systemToolbarInstance);
        layoutSystem.getCell("tabbar").attach(systemTabbarInstance);
        layoutSystem.getCell("sidebar").attach(systemSidebarInstance);
    }

    systemToolbarInstance.events.on("click", (id) => {
        let themeId;
        switch (id) {
            case "lightMode":
                themeId = "light";
                break;
            case "darkMode":
                themeId = "dark";
                break;
            case "autoMode":
                const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
                themeId = prefersDark ? "dark" : "light";
                break;
            default:
                return;
        }

        if (themeId) {
            if (dhx.setTheme && typeof dhx.setTheme === 'function') {
                dhx.setTheme(themeId);
            } else {
                if (window.dhx && typeof window.dhx.setTheme === 'function') {
                    window.dhx.setTheme(themeId);
                } else {
                    console.error("DHX Suite 核心方法 setTheme 未找到。");
                    return;
                }
            }

            if (layoutSystem) {
                layoutSystem.paint();
            }
        }
    });

    systemSidebarInstance.events.on("click", id => {
        if (id === "toggle") {
            const toggleItem = systemSidebarInstance.data.getItem("toggle");
            systemSidebarInstance.toggle();
            toggleItem.icon = systemSidebarInstance.config.collapsed ? "mdi mdi-menu" : "mdi mdi-backburger";
        }
    });

    return layoutSystem;
}

async function initBoardAbout() {
    boardAbout = new dhxLayout(null, boardAboutConfig);

    boardAbout.getCell("about").progressShow();
    const aboutHtml = await loadAboutContent();
    boardAbout.getCell("about").attachHTML(aboutHtml);
    boardAbout.getCell("about").progressHide();

    systemTabbarInstance.getCell("about").attach(boardAbout);
    return boardAbout;
}

function initBoardHome() {
    boardHome = new dhxLayout(null, boardHomeConfig);

    test2GridInstance = new dhxGrid(null, test2GridConfig);
    test2ContextMenuInstance = new dhxContextMenu(null, test2ContextMenuConfig);
    scanToolbarInstance = new dhxToolbar(null, scanToolbarConfig);
    scanGridInstance = new dhxGrid(null, scanGridConfig);

    test2GridInstance.data.parse(test2Data);
    // 将所有学生作为 scanGrid 的初始数据（包含 src 字段，初始为 null）
    try {
        if (Array.isArray(allStudentsPool) && allStudentsPool.length) {
            // Ensure each student has a `class` field (may be empty) so the grid's "班级" column shows correctly
            const initialStudents = allStudentsPool.map(s => ({ ...s, class: s.class || '' }));
            scanGridInstance.data.parse(initialStudents);
        }
    } catch (e) {
        console.warn('初始化 scanGrid 数据失败', e);
    }

    // Helper to update a row's src and expand the row
    // function updateScanRowSrc(studentId, srcUrl) {
    //     try {
    //         const items = [];
    //         if (scanGridInstance && scanGridInstance.data && typeof scanGridInstance.data.forEach === 'function') {
    //             scanGridInstance.data.forEach(item => items.push(item));
    //         }
    //         const rowItem = items.find(it => String(it.id) === String(studentId));
    //         if (!rowItem) return false;

    //         const updateObj = Object.assign({}, rowItem, { src: srcUrl });
    //         if (scanGridInstance.data.update) {
    //             try { scanGridInstance.data.update(rowItem.id, updateObj); } catch (e) { scanGridInstance.data.set(rowItem.id, updateObj); }
    //         } else if (scanGridInstance.data.set) {
    //             scanGridInstance.data.set(rowItem.id, updateObj);
    //         } else {
    //             const all = items.map(i => i.id === rowItem.id ? updateObj : i);
    //             scanGridInstance.data.parse(all);
    //         }

    //         try { if (typeof scanGridInstance.expand === 'function') scanGridInstance.expand(rowItem.id); } catch (e) { }
    //         try { if (scanGridInstance.selection && typeof scanGridInstance.selection.setCell === 'function') scanGridInstance.selection.setCell(rowItem.id); } catch (e) { }
    //         return true;
    //     } catch (e) {
    //         console.warn('updateScanRowSrc error', e);
    //         return false;
    //     }
    //     return true;
    // }

    boardHome.getCell("test2Grid").attach(test2GridInstance);
    boardHome.getCell("scanToolbar").attach(scanToolbarInstance);
    boardHome.getCell("scanGrid").attach(scanGridInstance);

    boardHome.getCell("scanColumn").hide();
    // test2Grid 绑定点击事件
    test2GridInstance.events.on("cellClick", (row, column, e) => {
        if (column.id === "actions" && e.target.classList.contains("row-menu")) {
            test2GridInstance.selection.setCell(row.id, column.id);
            test2ContextMenuInstance.showAt(e.target);
        }
    });
    test2ContextMenuInstance.events.on("click", id => {
        const row = test2GridInstance.selection.getCell()?.row;
        if (!row) return;

        console.log(`在测试 "${row.testName}" 上点击了菜单项: ${id}`);
        switch (id) {
            case "scan":
                // 记住当前扫描的测试名
                currentScanTestName = row.testName;

                // 将学生池加载到 scanGrid，并生成 src 路径
                try {
                    // Prefer building students list from `classData` so we can attach the correct class name.
                    let studentsWithSrc = [];
                    if (Array.isArray(classData) && classData.length) {
                        classData.forEach(cls => {
                            if (Array.isArray(cls.students)) {
                                cls.students.forEach(student => {
                                    studentsWithSrc.push({
                                        ...student,
                                        class: cls.className || '',
                                        // Use absolute path under `public/` (leading slash) so browser requests `/results/...`
                                        src: `/results/visualization_omr_${encodeURIComponent(row.testName)}_${student.id}.png`
                                    });
                                });
                            }
                        });
                    }

                    // Fallback to allStudentsPool if classData produced no entries
                    if (studentsWithSrc.length === 0 && Array.isArray(allStudentsPool)) {
                        studentsWithSrc = allStudentsPool.map(student => ({
                            ...student,
                            class: student.class || '',
                            src: `/results/visualization_omr_${encodeURIComponent(row.testName)}_${student.id}.png`
                        }));
                    }

                    scanGridInstance.data.parse(studentsWithSrc);
                } catch (e) {
                    console.warn('加载 students 到 scanGrid 失败', e);
                }

                boardHome.getCell("scanColumn").show();
                break;
        }
    });

    // scanToolbarInstance 绑定点击事件
    scanToolbarInstance.events.on("click", (id) => {
        if (id === "return") {
            boardHome.getCell("scanColumn").hide();
            return;
        }

        if (id === "upload") {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = 'image/png,image/jpeg';

            input.onchange = async (e) => {
                const file = e.target.files[0];
                if (!file) return;

                const testName = currentScanTestName || window.prompt('请输入测试名称 (例如: 2022年12月02日小测):');
                if (!testName) {
                    window.alert('上传已取消：未提供测试名称');
                    return;
                }

                // 获取当前选中的学号（行）作为默认学号；若存在则直接使用并跳过 prompt
                let selectedCell = scanGridInstance.selection.getCell?.();
                let defaultStudentId = selectedCell?.row?.id || '';
                let studentId = defaultStudentId;
                if (!studentId) {
                    studentId = window.prompt('请输入学号 (例如: 001):');
                    if (!studentId) {
                        window.alert('上传已取消：未提供学号');
                        return;
                    }
                }

                const formData = new FormData();
                formData.append('testName', testName);
                formData.append('studentId', studentId);
                formData.append('omrFile', file);

                try {
                    const resp = await window.axios.post('/api/upload-omr', formData, { headers: { 'Content-Type': 'multipart/form-data' } });
                    console.log('upload response', resp.data);
                    window.alert('上传成功: ' + (resp.data.path || ''));

                    // 上传后询问是否开始识别
                    if (window.confirm('是否现在执行识别？')) {
                        try {
                            const procResp = await window.axios.post('/api/process-omr', {
                                testName,
                                studentId,
                            });
                            console.log('process response', procResp.data);
                            const out = procResp.data.output || '';
                            const err = procResp.data.error || '';
                            window.alert('识别完成，脚本输出:\n' + out + '\n' + err);

                            // const srcUrl = procResp.data.visualization || `/results/visualization_omr_${testName}_${studentId}.png`;
                            // try {
                            //     updateScanRowSrc(studentId, srcUrl);
                            // } catch (uErr) {
                            //     console.warn('更新 src 失败: ', uErr);
                            // }
                        } catch (procErr) {
                            // 更友好的错误提示：优先显示后端返回的 message 或错误体
                            let errMsg = '识别失败';
                            try {
                                if (procErr && procErr.response && procErr.response.data) {
                                    const d = procErr.response.data;
                                    if (d.message) errMsg += '：' + d.message;
                                    else errMsg += '：' + JSON.stringify(d);
                                } else {
                                    errMsg += '：' + (procErr.message || String(procErr));
                                }
                            } catch (ee) {
                                errMsg += '（无法读取错误详情）';
                            }
                            console.error('处理失败', procErr);
                            window.alert(errMsg);
                        }
                    }
                } catch (uploadErr) {
                    console.error('上传失败', uploadErr);
                    window.alert('上传失败，请查看控制台或后端日志');
                }
            };

            document.body.appendChild(input);
            input.click();
            input.remove();
            return;
        }
    });

    // track last expanded row id (for collapse on next select)
    let lastExpandedId = null;
    // DOM references for manual subrow insertion fallback
    let lastClickedRowEl = null;
    let lastInsertedSubrow = null;

    function findRowElementFromEvent(e) {
        let el = e && e.target ? e.target : null;
        while (el && el !== document.body) {
            try {
                const cls = el.className || '';
                if (cls && (cls.indexOf('dhx_grid-row') !== -1 || cls.indexOf('dhx-grid-row') !== -1)) return el;
                if (el.getAttribute && (el.getAttribute('data-id') || el.getAttribute('data-row-id'))) return el;
                if (el.getAttribute && el.getAttribute('role') === 'row') return el;
            } catch (e) { /* ignore DOM exceptions */ }
            el = el.parentElement;
        }
        return null;
    }

    function createSubrowElement(rowData) {
        const wrapper = document.createElement('div');
        wrapper.className = 'dhx-grid-subrow';
        wrapper.style.padding = '12px 20px';
        wrapper.style.borderTop = '1px solid rgba(0,0,0,0.04)';
        wrapper.innerHTML = `
            <div class="dhx-appartment">
                ${rowData && rowData.src ? `
                    <div class="dhx-appartment__image dhx-appartment__container" style="background-image: url(${rowData.src})"></div>
                ` : `
                    <div class="dhx-appartment__image dhx-appartment__container dhx-appartment__noimage">无图片</div>
                `}
            </div>
        `;
        return wrapper;
    }

    function findRowElementByData(id, rowData) {
        // Prefer previously-captured element
        if (lastClickedRowEl) return lastClickedRowEl;

        // Try data attributes
        let el = document.querySelector(`[data-id="${id}"]`) || document.querySelector(`[data-row-id="${id}"]`);
        if (el) return el;

        // Try to find by matching visible text (id or name) in grid rows
        const rowCandidates = Array.from(document.querySelectorAll('.dhx_grid-row, .dhx-grid-row, [role="row"]'));
        const needleId = String(id || '').trim();
        const needleName = String((rowData && (rowData.name || rowData.testName)) || '').trim();
        for (const r of rowCandidates) {
            try {
                const txt = (r.textContent || '').trim();
                if (!txt) continue;
                if (needleId && txt.indexOf(needleId) !== -1) return r;
                if (needleName && txt.indexOf(needleName) !== -1) return r;
            } catch (e) { /* ignore DOM errors */ }
        }

        // Try more generic search anywhere in grid container
        const all = Array.from(document.querySelectorAll('*'));
        for (const a of all) {
            try {
                const txt = (a.textContent || '').trim();
                if (!txt) continue;
                if (needleId && txt.indexOf(needleId) !== -1) return a;
                if (needleName && txt.indexOf(needleName) !== -1) return a;
            } catch (e) { }
        }

        return null;
    }

    // When user clicks the expand cell, set selection — afterSelect will handle expand/collapse
    scanGridInstance.events.on("cellClick", (row, column, e) => {
        console.log('scanGrid cellClick', { row, column, target: e && e.target && (e.target.className || e.target.tagName) });
        if (column.id === "expand") {
            const rowId = row.id;
            // If image src exists, open it in a new tab for a simple, reliable preview
            const src = row && row.src;
            if (src) {
                // Ensure absolute URL: if starts with /, use location origin
                const url = src.startsWith('/') ? (window.location.origin + src) : src;
                try { window.open(url, '_blank'); return; } catch (err) { console.warn('window.open failed', err); }
            }

            // capture the clicked row DOM element for manual fallback insertion
            lastClickedRowEl = findRowElementFromEvent(e);
            try { scanGridInstance.selection.setCell(rowId); } catch (err) { console.warn('selection.setCell failed', err); }
        }
    });

    // Mirror dhtmlx example: collapse previous expanded row and expand the newly selected one
    scanGridInstance.events.on("afterSelect", ({ id }) => {
        console.log('afterSelect', { id, hasExpand: typeof scanGridInstance.expand, hasCollapse: typeof scanGridInstance.collapse });

        // Try collapse previous via API; otherwise clear $opened on previous row
        if (lastExpandedId) {
            if (typeof scanGridInstance.collapse === 'function') {
                try { scanGridInstance.collapse(lastExpandedId); } catch (e) { console.warn('collapse failed', e); }
            } else {
                const prev = scanGridInstance.data.getItem(lastExpandedId);
                if (prev && prev.$opened) {
                    delete prev.$opened;
                    try { scanGridInstance.data.update(lastExpandedId, prev); } catch (e) { try { scanGridInstance.data.set(lastExpandedId, prev); } catch (ee) { /* swallow */ } }
                }
            }
        }

        if (id) {
            if (typeof scanGridInstance.expand === 'function') {
                try {
                    scanGridInstance.expand(id);
                    console.log('called expand API for', id);
                    lastExpandedId = id;
                    return;
                } catch (e) {
                    console.warn('expand API failed', e);
                }
            }

            // Fallback: set $opened on the selected row and repaint; if that doesn't render, insert DOM subrow
            try {
                const rowData = scanGridInstance.data.getItem(id);
                if (rowData) {
                    rowData.$opened = true;
                    try { scanGridInstance.data.update(id, rowData); } catch (e) { try { scanGridInstance.data.set(id, rowData); } catch (ee) { /* swallow */ } }
                    try { if (typeof scanGridInstance.paint === 'function') scanGridInstance.paint(); } catch (e) { }
                    lastExpandedId = id;
                    console.log('fallback: set $opened and painted for', id, 'src=', rowData.src);

                    // Manual DOM insertion if the grid didn't show the subrow (insert after clicked row element)
                    try {
                        // remove previous inserted subrow
                        if (lastInsertedSubrow && lastInsertedSubrow.parentElement) {
                            lastInsertedSubrow.parentElement.removeChild(lastInsertedSubrow);
                            lastInsertedSubrow = null;
                        }

                        const rowEl = lastClickedRowEl || document.querySelector(`[data-id="${id}"]`) || document.querySelector(`[data-row-id="${id}"]`);
                        if (rowEl) {
                            const subEl = createSubrowElement(rowData);
                            // insert after rowEl
                            if (rowEl.nextSibling) rowEl.parentElement.insertBefore(subEl, rowEl.nextSibling);
                            else rowEl.parentElement.appendChild(subEl);
                            lastInsertedSubrow = subEl;
                        } else {
                            console.warn('could not find row DOM element for manual subrow insertion', id);
                        }
                    } catch (domErr) {
                        console.warn('manual subrow insertion failed', domErr);
                    }

                } else {
                    console.warn('no rowData for id', id);
                }
            } catch (e) {
                console.error('fallback expand failed', e);
            }
        }
    });

    let lastId = scanGridInstance.data.getId(0);
    scanGridInstance.selection.setCell(lastId);

    systemTabbarInstance.getCell("home").attach(boardHome);
    return boardHome;
}

function initBoardClass() {
    boardClass = new dhxLayout(null, boardClassConfig);

    classToolbarInstance = new dhxToolbar(null, classToolbarConfig);
    classGridInstance = new dhxGrid(null, classGridConfig);
    classContextMenuInstance = new dhxContextMenu(null, classContextMenuConfig);

    studentToolbarInstance = new dhxToolbar(null, studentToolbarConfig);
    studentDataviewInstance = new dhxDataview(null, studentDataviewConfig);

    classGridInstance.data.parse(classData);

    boardClass.getCell("classToolbar").attach(classToolbarInstance);
    boardClass.getCell("classGrid").attach(classGridInstance);
    boardClass.getCell("studentToolbar").attach(studentToolbarInstance);
    boardClass.getCell("studentDataview").attach(studentDataviewInstance);

    boardClass.getCell("studentColumn").hide();
    // classGrid 绑定点击事件
    classGridInstance.events.on("cellClick", (row, column, e) => {
        if (column.id === "actions" && e.target.classList.contains("row-menu")) {
            classGridInstance.selection.setCell(row.id, column.id);
            classContextMenuInstance.showAt(e.target);
        }
    });
    classContextMenuInstance.events.on("click", id => {
        const row = classGridInstance.selection.getCell()?.row;
        if (!row) return;

        console.log(`在班级 "${row.className}" 上点击了菜单项: ${id}`);
        switch (id) {
            case "edit":
                console.log(`编辑班级: ${row.className}`);
                // 获取学生数据并加载到 studentDataviewInstance
                if (row.students) {
                    studentDataviewInstance.data.parse(row.students);
                } else {
                    studentDataviewInstance.data.clear();
                }
                boardClass.getCell("studentColumn").show();
                break;
            case "delete":
                console.log(`删除班级: ${row.className}`);
                boardClass.getCell("studentColumn").hide();
                classGridInstance.data.remove(row.id);
                break;
        }
    });

    // studentToolbarInstance 绑定点击事件
    studentToolbarInstance.events.on("click", (id) => {
        if (id === "return") {
            boardClass.getCell("studentColumn").hide();
        }
    });

    systemTabbarInstance.getCell("class").attach(boardClass);
    return boardClass;
}

function initBoardTest() {
    boardTest = new dhxLayout(null, boardTestConfig);

    testToolbarInstance = new dhxToolbar(null, testToolbarConfig);
    testGridInstance = new dhxGrid(null, testGridConfig);
    testContextMenuInstance = new dhxContextMenu(null, testContextMenuConfig);
    sheetToolbarInstance = new dhxToolbar(null, sheetToolbarConfig);
    sheetGridInstance = new dhxGrid(null, sheetGridConfig);

    testGridInstance.data.$parse(testData);

    boardTest.getCell("testToolbar").attach(testToolbarInstance);
    boardTest.getCell("testGrid").attach(testGridInstance);
    boardTest.getCell("sheetToolbar").attach(sheetToolbarInstance);
    boardTest.getCell("sheetGrid").attach(sheetGridInstance);

    boardTest.getCell("sheetColumn").hide();
    // testGrid 绑定点击事件
    testGridInstance.events.on("cellClick", (row, column, e) => {
        if (column.id === "actions" && e.target.classList.contains("row-menu")) {
            testGridInstance.selection.setCell(row.id, column.id);
            testContextMenuInstance.showAt(e.target);
        }
    });
    testContextMenuInstance.events.on("click", id => {
        const row = testGridInstance.selection.getCell()?.row;
        if (!row) return;

        console.log(`在测试 "${row.testName}" 上点击了菜单项: ${id}`);
        switch (id) {
            case "edit":
                console.log(`编辑试卷: ${row.testName}`);
                // 保存当前编辑的测试信息
                currentEditingTest = row;
                // 获取当前测验的题目数据并加载
                if (row.sheets) {
                    sheetGridInstance.data.parse(row.sheets);
                } else {
                    // 如果没有题目数据，则清空表格
                    sheetGridInstance.data.clear();
                }
                boardTest.getCell("sheetColumn").show();
                break;
            case "delete":
                console.log(`删除测验: ${row.testName}`);
                boardTest.getCell("sheetColumn").hide();
                testGridInstance.data.remove(row.id);
                break;
        }
    });

    // sheetToolbarInstance 绑定点击事件
    sheetToolbarInstance.events.on("click", (id) => {
        if (id === "return") {
            boardTest.getCell("sheetColumn").hide();
            currentEditingTest = null;  // 清除当前编辑的测试
        }
    });

    // 新增：下载答题卡按钮处理
    sheetToolbarInstance.events.on("click", async (id) => {
        if (id !== "download") return;

        // 使用当前编辑的测试
        let selectedRow = currentEditingTest;

        if (!selectedRow) {
            window.alert("未找到可导出的测验数据，请先编辑一份测试");
            return;
        }

        const payload = {
            testName: selectedRow.testName || "Generated Test",
            omrSheets: selectedRow.sheets || []
        };

        try {
            // 使用 axios（bootstrap.js 已将 axios 挂到 window）
            const response = await window.axios.post('/api/generate-omr-card', payload, {
                responseType: 'blob'
            });

            const blob = new Blob([response.data], { type: 'image/png' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `omr_${(payload.testName || 'export').replace(/\s+/g, '_')}.png`;
            document.body.appendChild(a);
            a.click();
            a.remove();
            window.URL.revokeObjectURL(url);
        } catch (err) {
            console.error("生成答题卡失败：", err);
            window.alert("生成答题卡失败，请查看控制台或后端日志。");
        }
    });

    // sheetGridInstance 函数内部
    sheetGridInstance.events.on("load", () => {
        sheetGridInstance.data.forEach((item, index) => {
            item.questionId = index + 1;
        });
    });

    systemTabbarInstance.getCell("test").attach(boardTest);
    return boardTest;
}

function unload() {
    if (classContextMenuInstance) {
        classContextMenuInstance.destructor();
        classContextMenuInstance = null;
    }

    if (boardClass) {
        boardClass.destructor();
        boardClass = null;
    }
}

// 渲染布局
onMounted(() => {
    if (!container.value) return;
    initSystem();
    initBoardAbout();
    initBoardHome();
    initBoardClass();
    initBoardTest();
});
</script>

<style>
@import 'dhx-suite/codebase/suite.min.css';
@import "@mdi/font/css/materialdesignicons.min.css";

@import '../css/layoutSystem.css';
@import '../css/boardHome.css';
@import '../css/boardClass.css';
@import '../css/boardTest.css';
</style>
